import datetime
import os
import getpass
import random
import string

from absl import app, flags

from coin.support.feed_tool.feed_stats.app.feed_stats_motion.util import dump_stats_to_db
from coin.support.feed_tool.feed_stats.app.feed_latency_stats.util import dump_latency_stats_to_db
from coin.proto.coin_request_pb2 import ExchangeApiRequestProto

FLAGS = flags.FLAGS


def main(_):
  trading_date_str = FLAGS.trading_date
  assert trading_date_str is not None
  duration = FLAGS.duration
  if "T" in trading_date_str:
    trading_date = datetime.datetime.strptime(trading_date_str, "%Y%m%dT%H%M")
  else:
    trading_date = datetime.datetime.strptime(trading_date_str, "%Y%m%d")

  machine = FLAGS.machine
  (market_type, exchange, api_version) = tuple(FLAGS.mea.split('.'))
  recipe = FLAGS.recipe
  group = FLAGS.group
  worker = FLAGS.worker
  need_plot = FLAGS.need_plot
  need_feed_csv = FLAGS.need_feed_csv
  run_for_raw = FLAGS.run_for_raw
  interval = FLAGS.interval if FLAGS.interval != 'None' else None
  if (interval):
    assert (interval[-1]=="M" or interval[-1]=="H") , 'wrong interval setting , should be like 60M or 1H'
    if (interval[-1]=="M"):
      interval = int(int(interval[:-1])*60*1e9)
    else:
      interval = int(int(interval[:-1])*3600*1e9)
  dirpath = "/tmp/%s/coin_feed/%s-%s" % (
      getpass.getuser(),
      datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f"),
      ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)))
  print("Temperary data in %s" % dirpath)
  os.makedirs(dirpath, exist_ok=True)

  sub_request = ExchangeApiRequestProto(
      market_type=market_type,
      exchange=exchange,
      api_version=api_version
  )
  if FLAGS.latency_stat_only:
    args_dict = {
        'output_root': dirpath,
        'date_universe': [trading_date],
        'duration': duration,
        'sub_request': sub_request,
        'recipe': recipe,
        'group': group,
        'worker': worker,
        'machine': machine,
        'need_plot': need_plot,
        'need_feed_csv': need_feed_csv,
        'run_for_raw': run_for_raw,
        'interval': interval,
        'latency_stat_only': FLAGS.latency_stat_only,
    }
    dump_latency_stats_to_db(**args_dict)
  else:
    args_dict = {
        'output_root': dirpath,
        'date_universe': [trading_date],
        'duration': duration,
        'sub_request': sub_request,
        'recipe': recipe,
        'group': group,
        'worker': worker,
        'machine': machine,
        'need_plot': need_plot,
        'need_feed_csv': need_feed_csv,
        'run_for_raw': run_for_raw,
        'interval': interval,
    }
    dump_stats_to_db(**args_dict)


if __name__ == '__main__':
  flags.DEFINE_string('trading_date', None, 'yyyymmdd or yyyymmddTHHMM')

  flags.DEFINE_string('duration', 'PT24H', 'PT24H')

  flags.DEFINE_string('machine', None, 'Machine name.')

  flags.DEFINE_string('mea', None, 'market_type.exchange.api_version')

  flags.DEFINE_string('recipe', None, 'Recipe')

  flags.DEFINE_string('group', None, 'Single group name.')

  flags.DEFINE_integer('worker', 0, 'Worker id.')

  flags.DEFINE_boolean('need_plot', False, 'Whether plot is needed.')

  flags.DEFINE_boolean('need_feed_csv', False, 'Whether output feed into csv.')

  flags.DEFINE_boolean('run_for_raw', False, 'Whether run for raw feed.')
  
  flags.DEFINE_string('interval', None, 'interval time for interval feed generate, mmM or hhH')
  
  flags.DEFINE_boolean('latency_stat_only', False, 'Whether run to only generate latency stat for monitor')

  app.run(main)
